﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Networking
{

    /// <summary>
    /// Packet of type KeyEventPacket, it contains the information about the key/keys pressed/released
    /// </summary>
    public class KeyEventPacket : Packet
    {

        /// <summary>
        /// Whether the key is now up or down
        /// </summary>
        public bool DownFlag { get; private set; }

        /// <summary>
        /// The key being pressed/released
        /// </summary>
        public Keys Key { get; private set; }

        /// <summary>
        /// Creates a new instance of KeyEventPacket specifying all the parameters
        /// </summary>
        /// <param name="DownFlag">Whether the key is now up or down</param>
        /// <param name="Key">The key being pressed/released</param>
        public KeyEventPacket(bool DownFlag, Keys Key)
            : base(PacketType.KeyEvent)
        {
            this.DownFlag = DownFlag;
            this.Key = Key;
        }


        /// <summary>
        /// Creates a new instance of KeyEventPacket extracting all the parameters from the byte buffer
        /// </summary>
        /// <param name="buffer">The byte buffer containing the packet data</param>
        public KeyEventPacket(byte[] buffer)
            : base(PacketType.KeyEvent, buffer)
        {
            //
        }

        /// <summary>
        /// Serializes the packet in order to send it
        /// </summary>
        /// <returns>The bytes of the packet</returns>
        public override byte[] Serialize()
        {
            MemoryStream memory = new MemoryStream();

            BinaryWriter writer = new BinaryWriter(memory);

            writer.Write((byte)this.Type);

            writer.Write((byte)(this.DownFlag ? 0x1 : 0x0));

            writer.Write((int)this.Key);
                        
            writer.Close();

            return memory.ToArray();

        }


        /// <summary>
        /// Loads a packet from a byte buffer
        /// </summary>
        /// <param name="buffer">The data buffer</param>
        public override void Load(byte[] buffer)
        {
            if (buffer.Length != 6) throw new BufferSizeMismatchException(8);

            MemoryStream memory = new MemoryStream(buffer);

            BinaryReader reader = new BinaryReader(memory);

            this.Type = (PacketType)reader.ReadByte();

            if (this.Type != PacketType.KeyEvent)
                throw new PacketTypeMismatchException(PacketType.KeyEvent, this.Type);

            this.DownFlag = reader.ReadByte() == 0x1 ? true : false;

            this.Key = (Keys)reader.ReadInt32();

            reader.Close();

        }
    }
}
